/*
 * Name     : PeerReader.java
 * Author(s): Jill San Luis
 * Created  : Mar 14, 2011, 4:02:21 PM
 */
package mazewar.network;

import java.io.IOException;
import java.net.DatagramPacket;

import java.net.MulticastSocket;

import mazewar.utility.SimpleLogger;


/**
 * The PeerReader class
 *
 * @author  Jill San Luis
 */
public class PeerReader extends Thread {

    private MazewarNodeConfig config = MazewarNodeConfig.getInstance();
    private SimpleLogger logger = SimpleLogger.getInstance();
    private MulticastSocket socket;
    private MazewarNode ownerInfo;

    /**
     * Creates a new instance of PeerReader.
     */
    public PeerReader(MazewarNode ownerInfo) throws InstantiationException {

        this.ownerInfo = ownerInfo;

        try {
            socket = new MulticastSocket(config.getDefaultMulticastPort()); // must bind receive side
            socket.joinGroup(config.getMulticastAddress().getAddress());
        } catch (IOException ex) {
            throw new InstantiationException("Cannot initialize reader. " + ex.getMessage());
        }

        this.run();
    }

    @Override
    public void run() {

        byte[] b = new byte[config.getBufferLength()];
        DatagramPacket dgram = new DatagramPacket(b, b.length);
        while (true) {

            try {
                socket.receive(dgram); // blocks until a datagram is received
                logger.log(PeerReader.class.getSimpleName(), "Received " + dgram.getLength() + " bytes from " + dgram.getAddress());
                dgram.setLength(b.length); // must reset length field!
            } catch (IOException e) {
                logger.log(PeerReader.class.getSimpleName(), e.getMessage());
            }
        }
    }
}
